/*
 * @Company: zmn
 * @Author: tangmaoqin
 * @Description:
 * @Date: 2024-08-11 09:32:09
 */
import { ANDROID_PERMISSIONS_ENUM, AuthCodeEnum, AuthEnum } from '../enums';
import { queryPermissionNamesByPermissionId } from '../tools';
import { IAuthResponse } from '../types';

/** 检查Android系统的设备服务GPS是否开启 */
export const checkAndroid_GPS_Service = () => {
  const context = plus.android.importClass('android.content.Context');
  const locationManager = plus.android.importClass('android.location.LocationManager');
  const main = plus.android.runtimeMainActivity();
  const mainSvr = main.getSystemService(context.LOCATION_SERVICE);
  const result = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
  console.log(`系统定位开启:${result}`);
  return result;
};

/**
 * 检查Android权限
 * @param permission 权限名称
 * @returns {IAuthResponse}
 */
export const checkAndroidPermissions = (permission: ANDROID_PERMISSIONS_ENUM | string): IAuthResponse => {
  if (permission === ANDROID_PERMISSIONS_ENUM.GPS) {
    const gpsRes = checkAndroid_GPS_Service();
    return {
      code: gpsRes ? AuthCodeEnum.AUTHORIZED : AuthCodeEnum.DENIED,
      data: gpsRes,
      message: `permission is ${gpsRes ? AuthEnum.AUTHORIZED : AuthEnum.DENIED}`,
    };
  }
  const authRes = plus.navigator.checkPermission(permission as PlusNavigatorPermissionNames);
  const AndroidAuthCodeMap = {
    [AuthEnum.AUTHORIZED]: AuthCodeEnum.AUTHORIZED,
    [AuthEnum.DENIED]: AuthCodeEnum.DENIED,
    [AuthEnum.UNDETERMINED]: AuthCodeEnum.UNDETERMINED,
    [AuthEnum.NOTDENY]: AuthCodeEnum.NOTDENY,
    [AuthEnum.UNKNOWN]: AuthCodeEnum.UNKNOWN,
    [AuthEnum.UNSUPPORTED]: AuthCodeEnum.UNSUPPORTED,
    [AuthEnum.UNDEFINED]: AuthCodeEnum.UNDEFINED,
  };
  return {
    code: AndroidAuthCodeMap[authRes],
    data: authRes === AuthEnum.AUTHORIZED,
    message: `permission is ${authRes}`,
  };
};

/**
 * 唤起权限弹窗
 * @param options
 * @returns
 */
// Android权限查询
export const requestAndroidPermission = (permission: string[] | string) => {
  const permissions = Array.isArray(permission) ? permission : [permission];
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  return new Promise<{ success: boolean; message: string; code?: number }>((resolve) => {
    plus.android.requestPermissions(
      permissions, // 理论上支持多个权限同时查询，但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
      function (resultObj) {
        console.log('checkAndroidPermissions', resultObj);

        let result = 0;
        for (let i = 0; i < resultObj.granted.length; i++) {
          const grantedPermission = resultObj.granted[i];
          console.log(`已获取的权限：${grantedPermission}`);
          result = 1;
        }
        for (let i = 0; i < resultObj.deniedPresent.length; i++) {
          const deniedPresentPermission = resultObj.deniedPresent[i];
          console.log(`拒绝本次申请的权限：${deniedPresentPermission}`);
          result = 0;
        }
        for (let i = 0; i < resultObj.deniedAlways.length; i++) {
          const deniedAlwaysPermission = resultObj.deniedAlways[i];
          console.log(`永久拒绝申请的权限：${deniedAlwaysPermission}`);
          result = -1;
        }
        resolve({
          success: result === 1,
          message: result === 1 ? '申请权限成功' : '申请权限失败',
        });
        // 若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
        // eslint-disable-next-line eqeqeq
        if (result != 1) {
          console.log('请打开权限', resultObj);
          // gotoAppPermissionSetting()
        }
      },
      function (error) {
        console.log(`申请权限错误：${error.code} = ${error.message}`);
        resolve({
          success: false,
          code: error.code,
          message: error.message,
        });
      }
    );
  });
};

/**
 * 调用安卓系统权限授权弹窗
 * @param permission
 * @returns
 */

export const invokeAndroidSystemAuthorizationPopup = async (permission: string[] | string) => {
  const AuthName = queryPermissionNamesByPermissionId({
    permission,
    platform: 'android',
  }) as string[];
  let AuthNames = Array.isArray(AuthName) ? AuthName : [AuthName];
  AuthNames = AuthNames.filter((authName) => authName !== ANDROID_PERMISSIONS_ENUM.GPS);
  console.log('AuthNames', AuthNames);
  const res = await requestAndroidPermission(AuthNames);
  return Promise.resolve(res);
};
